package slhs.tempo.TableAnalyzer;

import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;


public class SubjectListSelectionListener implements ListSelectionListener {

	private final String SUBJECT_FILTER = "Subject Filter";

	private Object[] selectedValues;
	private TablePanelHandler tablePanelHandlerObject;
	private StringBuffer regExpBuffer;
	private String regExp;

	public SubjectListSelectionListener(TablePanelHandler tablePanelHandler) {
		this.tablePanelHandlerObject = tablePanelHandler;
		this.regExpBuffer = new StringBuffer();
	}

	@Override
	public void valueChanged(ListSelectionEvent e) {
		JList list = (JList) e.getSource();

		int firstIndex = e.getFirstIndex();
		int lastIndex = e.getLastIndex();
		boolean isAdjusting = e.getValueIsAdjusting();

		if (list.getSelectionModel().isSelectionEmpty()) {
			JOptionPane.showMessageDialog(null, "Choose at least one subject",
					"Warning", JOptionPane.WARNING_MESSAGE);
		} else {
			// Find out which indexes are selected.
			selectedValues = list.getSelectedValues();

			// this is just a test as to whether the filter works
			if (isAdjusting == false) {
				// construct a regular expression from all the selected values
				// and apply the filter
				regExpBuffer = new StringBuffer();

				for (int selectionIndex = 0; selectionIndex < selectedValues.length; selectionIndex++) {
					regExpBuffer.append(selectedValues[selectionIndex]
							.toString() + "|");
					regExp = regExpBuffer.toString();
				}
				tablePanelHandlerObject.columnTextFilter(
						regExp.substring(0, (regExp.length() - 1)), 0,
						tablePanelHandlerObject.getColumnTextFilterIndex(SUBJECT_FILTER));
			}
		}
	}

}
